<?php

class Groups_GroupsController extends Zend_Controller_Action {

    public function init() {
        /* Initialize action controller here */
    }

    public function indexAction() {
        $groups = new Groups_Model_DbTable_Groups();
        $this->view->groups = $groups->fetchAll();
    }

    public function addAction() {
        $form = new Groups_Form_Group();

        if ($this->getRequest()->isPost()) {
            $formData = $this->getRequest()->getPost();
            if ($form->isValid($formData)) {
                $groupForm = new Groups_Model_DbTable_Groups();
                unset($formData['submit']);
                $groupForm->add($formData);
                $this->_helper->FlashMessenger()->setNamespace('success')->addMessage('grupo de usuario con exito.');
                $this->_helper->redirector->gotoUrlAndExit('/groups/groups/index');
            } else {
                $form->populate($formData);
                $this->view->form = $form;
            }
        } else {
            $this->view->form = $form;
        }
    }

    public function editAction() {
        $id = $this->_getParam('id', 'none');
        if (!is_numeric($id) or $id <= 0) {
            $this->_helper->FlashMessenger()->setNamespace('error')->addMessage('Ha ocurrido un error en la URL.');
            $this->_helper->redirector->gotoUrlAndExit('/groups/groups/index');
        }
        $form = new Groups_Form_Group();
        if ($this->getRequest()->isPost()) {
            $formData = $this->getRequest()->getPost();
            if ($form->isValid($formData)) {
                unset($formData['submit']);
                $group = new Groups_Model_DbTable_Groups();
                $group->update($formData, "idgroup=" . (int) $id);
                $this->_helper->FlashMessenger()->setNamespace('success')->addMessage('grupo Modificado con exito.');
                $this->_helper->redirector->gotoUrlAndExit('/groups/groups/index');
            } else {
                $form->populate($formData);
                $this->view->form = $form;
            }
        } else {
            $formData = new Groups_Model_DbTable_Groups();
            $formData = $formData->fetchRow("idgroup=" . $id)->toArray();
            $form->populate($formData);
            $this->view->form = $form;
        }
    }

}

